package com.zenithmind.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.article.mapper.CommentMapper;
import com.zenithmind.article.pojo.domain.Comment;
import com.zenithmind.article.pojo.query.CommentQuery;
import com.zenithmind.article.pojo.vo.CommentPageVO;
import com.zenithmind.article.service.CommentService;
import com.zenithmind.common.result.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Override
    public Comment addComment(Comment comment) {
        if (StringUtils.isBlank(comment.getArticleId())){
            throw new RuntimeException("文章ID不能为空");
        }
        if (StringUtils.isBlank(comment.getUserId())){
            throw new RuntimeException("用户ID不能为空");
        }
        if (StringUtils.isBlank(comment.getContent())){
            throw new RuntimeException("评论内容不能为空");
        }
        this.save(comment);
        return comment;
    }

    @Override
    public PageResult<CommentPageVO> pageComment(CommentQuery commentQuery) {
        Page<Comment> page = commentQuery.toPage();

        // 查询评论列表
        Page<Comment> commentPage = lambdaQuery()
                .eq(StringUtils.isNotBlank(commentQuery.getArticleId()), Comment::getArticleId, commentQuery.getArticleId())
                .eq(StringUtils.isNotBlank(commentQuery.getUserId()), Comment::getUserId, commentQuery.getUserId())
                .eq(StringUtils.isNotBlank(commentQuery.getParentId()), Comment::getParentId, commentQuery.getParentId())
                .eq(commentQuery.getStatus() != null, Comment::getStatus, commentQuery.getStatus())
                .page(page);

        // 将Comment转换为CommentPageVO
        List<CommentPageVO> commentVOList = commentPage.getRecords().stream()
                .map(comment -> {
                    CommentPageVO commentVO = new CommentPageVO();
                    BeanUtils.copyProperties(comment, commentVO);

                    // 如果是父评论，查询其子评论
                    if (StringUtils.isBlank(comment.getParentId())) {
                        // 查询所有子评论
                        List<Comment> childComments = lambdaQuery()
                                .eq(Comment::getParentId, comment.getId())
                                .eq(Comment::getStatus, 1) // 只查询已通过审核的评论
                                .list();
                        
                        // 如果有子评论，转换为VO列表
                        if (childComments != null && !childComments.isEmpty()) {
                            List<CommentPageVO> childCommentVOs = childComments.stream()
                                    .map(childComment -> {
                                        CommentPageVO childCommentVO = new CommentPageVO();
                                        BeanUtils.copyProperties(childComment, childCommentVO);
                                        return childCommentVO;
                                    })
                                    .collect(Collectors.toList());
                            commentVO.setChildComment(childCommentVOs);
                        }
                    }
                    
                    return commentVO;
                })
                .collect(Collectors.toList());

        // 返回正确的PageResult
        return new PageResult<>(commentVOList, commentPage.getTotal(), commentPage.getCurrent(), commentPage.getSize());
    }

    @Override
    public Comment saveOrUpdateComment(Comment comment) {
        if (StringUtils.isBlank(comment.getId())) {
            // 检查文章id和用户id是否存在
            if (StringUtils.isBlank(comment.getArticleId())){
                throw new RuntimeException("文章ID不能为空");
            }
            if (StringUtils.isBlank(comment.getUserId())){
                throw new RuntimeException("用户ID不能为空");
            }
            // 添加评论
            return addComment(comment);
        } else {
            // 更新评论
            this.updateById(comment);
            return comment;
        }
    }

    @Override
    public void reviewComment(String id, Integer status) {
        Comment comment = getById(id);
        if (comment == null) {
            throw new IllegalArgumentException("评论不存在");
        }

        // 更新评论状态 - 使用业务方法
        if (status == 1) {
            comment.approve(); // 审核通过
        } else if (status == 2) {
            comment.reject(); // 审核拒绝
        } else if (status == 3) {
            comment.delete(); // 删除
        } else {
            // 使用 setStatusCode 方法
            comment.setStatusCode(status);
        }
        updateById(comment);
    }

    @Override
    public Object getCommentStatistics() {
        // 评论统计信息
        Map<String, Object> statistics = new HashMap<>();
        
        // 评论总数
        long totalCount = count();
        statistics.put("totalCount", totalCount);
        
        // 今日评论数
        LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        long todayCount = count(new LambdaQueryWrapper<Comment>()
                .ge(Comment::getCreateTime, today));
        statistics.put("todayCount", todayCount);
        
        // 待审核评论数
        long pendingCount = count(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getStatus, 0));
        statistics.put("pendingCount", pendingCount);
        
        // 已通过评论数
        long approvedCount = count(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getStatus, 1));
        statistics.put("approvedCount", approvedCount);
        
        // 已拒绝评论数
        long rejectedCount = count(new LambdaQueryWrapper<Comment>()
                .eq(Comment::getStatus, 2));
        statistics.put("rejectedCount", rejectedCount);
        
        return statistics;
    }
}
